package com.easycoding.framework.repository.support.query;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;




/**
 * 创建查询信息
 * @author Wangjk
 * @Date 2013-9-24
 * @Version 1.0
 */
public class BuildQueryHandler<T> {
	
	private static final Log log = LogFactory.getLog(BuildQueryHandler.class);
	
	/**
	 * 根据queryInfo信息转化成JPA查询条件
	 * @param queryInfo
	 * @return
	 */
	public Specification<T> buildSpecification(QueryInfo<T> queryInfo){
		if(log.isDebugEnabled())
			log.debug("queryInfo转化为JPA查询条件开始----------");
		if(queryInfo != null){
			//获取查询参数
			return new QueryInfoSpecification<T>(queryInfo);
		}
		return null;
	}
	
	/**
	 * 创建排序
	 * @param queryInfo
	 * @return
	 */
	public Sort buildSort(QueryInfo<T> queryInfo){
		if(queryInfo != null && queryInfo.getOrderBy() != null){
			Map<String,Direction> orderBy = queryInfo.getOrderBy();
			if(log.isDebugEnabled())
				log.debug("排序规则-------------");
			Sort.Order[] sorts = new Sort.Order[orderBy.size()];
			int i = 0;
			for(Entry<String, Direction> order : queryInfo.getOrderBy().entrySet()){
				if(log.isDebugEnabled()){
					log.debug("字段："+order.getKey() + " 方式:" + order.getValue().toString());
				}
				sorts[i] = new Sort.Order(order.getValue(),order.getKey());
				i ++ ;
			}
			return new Sort(sorts);
		}
		return null;
	}
}